/* This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://sam.zoy.org/wtfpl/COPYING for more details. A copy of the
 * WTFPL version 2 is provided in the source archive, at
 * example/WTFPL-2 .*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <fake437.hpp>

namespace {
  bool map[F437_DEFAULT_HEIGHT][F437_DEFAULT_WIDTH];

  int loc_x = 0;
  int loc_y = 0;

  void prepare_map(void) {
    for (int y(0) ; y < F437_DEFAULT_HEIGHT ; ++y) {
      for (int x(0) ; x < F437_DEFAULT_WIDTH ; ++x) {
        map[y][x] = !(std::rand() % 25);
      }
    }
    map[0][0] = false;
  }

  void draw_map(fake437::Surface* f437) {
    for (int y(0) ; y < F437_DEFAULT_HEIGHT ; ++y) {
      for (int x(0) ; x < F437_DEFAULT_WIDTH ; ++x) {
        f437->put_char(x, y,
                       map[y][x] ? 219 : 32,
                       F437_COLOR_WHITE,
                       F437_COLOR_BLACK);
      }
    }
  }

  void draw_guy(fake437::Surface* f437) {
    f437->put_char(loc_x, loc_y, 2,
                   F437_COLOR_BRED,
                   F437_COLOR_TRANSPARENT);
  }
}

extern "C"
int main(int argc, char* argv[]) {
  (void)argc;
  (void)argv;
  std::srand(std::time(NULL));
  prepare_map();
  SDL_Init(SDL_INIT_VIDEO);
  const F437Font* font = f437_get_font(F437_FONT_8x14);
  SDL_Surface* screen =
    SDL_SetVideoMode(F437_DEFAULT_WIDTH * font->char_width,
                     F437_DEFAULT_HEIGHT * font->char_height, 0, 0);
  fake437::Surface f437(screen, font);
  bool done = false;
  while (!done) {
    draw_map(&f437);
    draw_guy(&f437);
    SDL_Flip(screen);
    SDL_Event ev;
    while (SDL_PollEvent(&ev)) {
      if (ev.type == SDL_KEYDOWN) {
        switch (ev.key.keysym.sym) {
        case SDLK_ESCAPE: done = 1; break;
        case SDLK_UP:
          if (loc_y != 0 &&
              !map[loc_y - 1][loc_x]) {
            loc_y--;
          }
          break;
        case SDLK_DOWN:
          if (loc_y != F437_DEFAULT_HEIGHT - 1 &&
              !map[loc_y + 1][loc_x]) {
            loc_y++;
          }
          break;
        case SDLK_LEFT:
          if (loc_x != 0 &&
              !map[loc_y][loc_x - 1]) {
            loc_x--;
          }
          break;
        case SDLK_RIGHT:
          if (loc_x != F437_DEFAULT_WIDTH - 1 &&
              !map[loc_y][loc_x + 1]) {
            loc_x++;
          }
          break;
        default: break;
        }
      }
    }
  }
  return 0;
}
